/**
 * 
 */
package com.googlecode.iant.internal.builder;

import java.io.File;
import java.util.List;

import org.apache.ivy.ant.IvyRetrieve;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Jar;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;

import com.googlecode.iant.AntFacade;
import com.googlecode.iant.IvyFacade;
import com.googlecode.iant.builder.IProjectBuilder;
import com.googlecode.iant.project.IFolder;
import com.googlecode.iant.project.IProject;
import com.googlecode.iant.project.IProjectStructure;

/**
 * @author ccpascu
 *
 */
public class ProjectBuilder implements IProjectBuilder {

	/* (non-Javadoc)
	 * @see com.googlecode.iant.builder.IProjectBuilder#build(com.googlecode.iant.project.IProject)
	 */
	@Override
	public void build(IProject project) {
		resolveDependencies(project);
		compile(project);
		pack(project);
	}

	public void resolveDependencies(IProject project) {
		//final List<IDependency> dependencies = project.getDependencies();
		IvyRetrieve retrieve = IvyFacade.retrieveTask();
		final Project antProject = project.getAntProject();
		retrieve.setProject(antProject);
		retrieve.execute();
	}

	public final void pack(IProject project) {
		final Project antProject = project.getAntProject();
		Jar jar = AntFacade.newJarTask(antProject);
		File outputFile = new File(antProject.getBaseDir(), "target/" + antProject.getBaseDir().getName() + ".jar");
		final File outputFolder = new File(antProject.getBaseDir(), "target/classes");
		jar.setDestFile(outputFile);
		jar.setBasedir(outputFolder);
		jar.execute();
		
		
		final IProjectStructure structure = project.getStructure();
		final List<IFolder> sourceFolders = structure.getSourceFolders();
		jar = AntFacade.newJarTask(antProject);
		outputFile = new File(antProject.getBaseDir(), "target/" + antProject.getBaseDir().getName() + "-sources.jar");
		jar.setDestFile(outputFile);
		for (IFolder folder : sourceFolders) {
			final FileSet fileSet = new FileSet();
			fileSet.setDir(new File(antProject.getBaseDir(), folder.getName()));
			jar.addFileset(fileSet);
		}
		jar.execute();
	}

	public void compile(IProject project) {
		final Project antProject = project.getAntProject();
		final Javac javac = AntFacade.newJavacTask(antProject);
		javac.setProject(antProject);
		List<IFolder> sourceFolders = project.getStructure().getSourceFolders();
		for (IFolder folder : sourceFolders) {
			final Path path = new Path(antProject, folder.getName());
			javac.setSrcdir(path);
		}
		final File outputFolder = new File(antProject.getBaseDir(), "target/classes");
		outputFolder.mkdirs();
		javac.setDestdir(outputFolder);
		javac.execute();
	}

}
